package com.just.login.service;

import com.just.login.Model.User;
import com.just.login.Utils.Md5Utils;
import com.just.login.Utils.MyStringUtils;
import com.just.login.dao.Userdao;
import com.just.login.realm.CustomerMd5Realm;
import com.just.login.scanner.DaoScanner;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.StringUtils;

import java.io.IOException;
import java.util.Optional;

public class UserService {
    DaoScanner scanner = new DaoScanner();
    Userdao dao = (Userdao) scanner.getComponent("com.just.login.dao.Userdao");

    public void doLogin(User user) {
        // 创建manager
        DefaultSecurityManager securityManager = new DefaultSecurityManager();
        // 设置匹配器
        HashedCredentialsMatcher cm = new HashedCredentialsMatcher();
        cm.setHashAlgorithmName("md5");
        // 创建realm并注入匹配器
        CustomerMd5Realm realm = new CustomerMd5Realm();
        realm.setCredentialsMatcher(cm);
        // 注入realm
        securityManager.setRealm(realm);
        // 工具类设置manger
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        System.out.println(token);
        try {
            subject.login(token);
            System.out.println("登录成功");
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("认证失败，不存在该用户");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            System.out.println("认证失败，密码错误");
        }

    }



    public void doRegister(User user) {
        String salt = MyStringUtils.getRandomString(7);
        user.setSalt(salt);
        System.out.println(salt);
        user = Md5Utils.md5(user);
        dao.InsertUser(user);
    }
}
